<template>
  <AdminLayout active-menu="user-management">
    <div class="user-management-content">
      <div class="content-header">
        <h2>用户管理</h2>
        <p>管理平台用户信息</p>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="search-filter-section">
        <el-card class="filter-card">
          <div class="search-section">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户姓名、邮箱、电话..."
              clearable
              style="width: 350px; margin-right: 15px;"
              @input="handleSearch"
            >
              <template #suffix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>

          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="用户状态">
              <el-select v-model="filterForm.status" placeholder="选择状态" clearable @change="handleFilter">
                <el-option label="全部" value=""></el-option>
                <el-option label="正常" value="active"></el-option>
                <el-option label="禁用" value="disabled"></el-option>
                <el-option label="待验证" value="pending"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户类型">
              <el-select v-model="filterForm.type" placeholder="选择类型" clearable @change="handleFilter">
                <el-option label="全部" value=""></el-option>
                <el-option label="普通用户" value="user"></el-option>
                <el-option label="房东" value="landlord"></el-option>
                <el-option label="中介" value="agent"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleFilter">筛选</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 用户列表 -->
      <div class="user-list-section">
        <el-card class="list-card">
          <template #header>
            <div class="card-header">
              <span>用户列表 ({{ filteredUsers.length }})</span>
              <div class="header-actions">
                <el-button type="warning" @click="batchDisable" :disabled="selectedUsers.length === 0">
                  批量禁用 ({{ selectedUsers.length }})
                </el-button>
                <el-button type="success" @click="batchEnable" :disabled="selectedUsers.length === 0">
                  批量启用 ({{ selectedUsers.length }})
                </el-button>
              </div>
            </div>
          </template>

          <el-table 
            :data="paginatedUsers" 
            @selection-change="handleSelectionChange"
            style="width: 100%"
            class="user-table"
            stripe
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="用户ID" width="100" />
            <el-table-column prop="avatar" label="头像" width="80">
              <template #default="scope">
                <el-avatar :size="40" :src="scope.row.avatar" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="email" label="邮箱" width="200" />
            <el-table-column prop="phone" label="电话" width="130" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="scope">
                <el-tag :type="getTypeTagType(scope.row.type)">
                  {{ getTypeText(scope.row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="registerTime" label="注册时间" width="160" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewDetails(scope.row)">详情</el-button>
                <el-button 
                  size="small" 
                  :type="scope.row.status === 'active' ? 'warning' : 'success'"
                  @click="toggleUserStatus(scope.row)"
                >
                  {{ scope.row.status === 'active' ? '禁用' : '启用' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="filteredUsers.length"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>

      <!-- 详情对话框 -->
      <el-dialog v-model="dialogVisible" title="用户详情" width="600px">
        <div v-if="currentUser" class="user-details">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{ currentUser.name }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ currentUser.phone }}</el-descriptions-item>
            <el-descriptions-item label="用户类型">
              <el-tag :type="getTypeTagType(currentUser.type)">
                {{ getTypeText(currentUser.type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(currentUser.status)">
                {{ getStatusText(currentUser.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="注册时间" :span="2">{{ currentUser.registerTime }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button 
            :type="currentUser && currentUser.status === 'active' ? 'warning' : 'success'"
            @click="toggleUserStatus(currentUser)"
          >
            {{ currentUser && currentUser.status === 'active' ? '禁用用户' : '启用用户' }}
          </el-button>
        </template>
      </el-dialog>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AdminLayout from '@/components/layout/AdminLayout.vue'
import { Search } from '@element-plus/icons-vue'

// 搜索关键词
const searchKeyword = ref('')

// 筛选表单
const filterForm = reactive({
  status: '',
  type: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框控制
const dialogVisible = ref(false)
const currentUser = ref(null)

// 选中的用户
const selectedUsers = ref([])

// 模拟用户数据
const users = ref([
  {
    id: 'U001',
    name: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    type: 'user',
    status: 'active',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    registerTime: '2024-01-15 10:30:00'
  },
  {
    id: 'U002',
    name: '李四',
    email: 'lisi@example.com',
    phone: '13800138002',
    type: 'landlord',
    status: 'active',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    registerTime: '2024-01-14 09:45:00'
  },
  {
    id: 'U003',
    name: '王五',
    email: 'wangwu@example.com',
    phone: '13800138003',
    type: 'agent',
    status: 'disabled',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    registerTime: '2024-01-13 08:20:00'
  }
])

// 筛选后的用户
const filteredUsers = computed(() => {
  let result = users.value

  // 搜索过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(user => 
      user.name.toLowerCase().includes(keyword) ||
      user.email.toLowerCase().includes(keyword) ||
      user.phone.includes(keyword)
    )
  }

  // 状态过滤
  if (filterForm.status) {
    result = result.filter(user => user.status === filterForm.status)
  }

  // 类型过滤
  if (filterForm.type) {
    result = result.filter(user => user.type === filterForm.type)
  }

  return result
})

// 分页后的用户
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
}

// 重置筛选
const resetFilters = () => {
  Object.assign(filterForm, {
    status: '',
    type: ''
  })
  searchKeyword.value = ''
  handleFilter()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    active: 'success',
    disabled: 'danger',
    pending: 'warning'
  }
  return types[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    active: '正常',
    disabled: '禁用',
    pending: '待验证'
  }
  return texts[status] || status
}

// 获取类型标签类型
const getTypeTagType = (type) => {
  const types = {
    user: 'primary',
    landlord: 'success',
    agent: 'warning'
  }
  return types[type] || ''
}

// 获取类型文本
const getTypeText = (type) => {
  const texts = {
    user: '普通用户',
    landlord: '房东',
    agent: '中介'
  }
  return texts[type] || type
}

// 查看详情
const viewDetails = (user) => {
  currentUser.value = user
  dialogVisible.value = true
}

// 切换用户状态
const toggleUserStatus = async (user) => {
  const action = user.status === 'active' ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(`确定${action}用户 ${user.name} 吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    user.status = user.status === 'active' ? 'disabled' : 'active'
    ElMessage.success(`用户已${action}`)
    dialogVisible.value = false
  } catch {
    // 用户取消
  }
}

// 批量禁用
const batchDisable = async () => {
  const activeUsers = selectedUsers.value.filter(user => user.status === 'active')
  if (activeUsers.length === 0) {
    ElMessage.warning('没有可禁用的用户')
    return
  }

  try {
    await ElMessageBox.confirm(`确定批量禁用选中的 ${activeUsers.length} 个用户吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    activeUsers.forEach(user => {
      user.status = 'disabled'
    })
    
    ElMessage.success(`成功禁用 ${activeUsers.length} 个用户`)
    selectedUsers.value = []
  } catch {
    // 用户取消
  }
}

// 批量启用
const batchEnable = async () => {
  const disabledUsers = selectedUsers.value.filter(user => user.status === 'disabled')
  if (disabledUsers.length === 0) {
    ElMessage.warning('没有可启用的用户')
    return
  }

  try {
    await ElMessageBox.confirm(`确定批量启用选中的 ${disabledUsers.length} 个用户吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    disabledUsers.forEach(user => {
      user.status = 'active'
    })
    
    ElMessage.success(`成功启用 ${disabledUsers.length} 个用户`)
    selectedUsers.value = []
  } catch {
    // 用户取消
  }
}

onMounted(() => {
  // 页面加载时的初始化
})
</script>

<style scoped>
.user-management-content {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}

.user-management-content::-webkit-scrollbar {
  width: 8px;
}

.user-management-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.user-management-content::-webkit-scrollbar-thumb {
  background: rgba(0, 195, 255, 0.6);
  border-radius: 4px;
}

.user-management-content::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 195, 255, 0.8);
}

.content-header {
  text-align: center;
  margin-bottom: 30px;
}

.content-header h2 {
  color: #2c3e50;
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 10px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-header p {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
}

/* 搜索筛选区域 */
.search-filter-section {
  margin-bottom: 20px;
}

.filter-card {
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid rgba(0, 195, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 195, 255, 0.1);
}

.search-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: end;
}

/* 列表区域 */
.user-list-section {
  margin-bottom: 20px;
}

.list-card {
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid rgba(0, 195, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 195, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 表格样式 */
.user-table {
  background: transparent;
}

.user-table :deep(.el-table__header th) {
  background: rgba(0, 195, 255, 0.15) !important;
  color: #2c3e50 !important;
  font-weight: 600;
  border-bottom: 2px solid rgba(0, 195, 255, 0.3);
}

.user-table :deep(.el-table__row) {
  background: rgba(255, 255, 255, 0.9) !important;
}

.user-table :deep(.el-table__row:hover) {
  background: rgba(0, 195, 255, 0.1) !important;
}

.user-table :deep(.el-table__row--striped) {
  background: rgba(248, 249, 250, 0.9) !important;
}

.user-table :deep(.el-table__row--striped:hover) {
  background: rgba(0, 195, 255, 0.1) !important;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 详情样式 */
.user-details {
  margin: 20px 0;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .search-section {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .filter-form {
    flex-direction: column;
  }

  .filter-form .el-form-item {
    width: 100%;
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .user-management-content {
    padding: 15px;
  }
  
  .content-header h2 {
    font-size: 24px;
  }
}
</style>
